<template>
  <div class="container">
    <data-view
      ref='dvDataView'
      propViewKey="dept_po_auto"
      :propFlowKey="propFlowKey"
      :propPageSize="500"
      :propCustomCols="myPropCustomCols"
      :propNoShowOverflow="true"
      @extra-button-click="extraButtonClick"
      :propColumnButton="true"
      :propNoEditRow="true"
      @after-load="afterLoad"
      propEditConfigMode="cell"
      @select-change="selectChange"
      @customSelectFocus="customSelectFocus"
      :propShowToolBar="true"
      class="data-view"
      :propPreQueryWrapper="$newWrapper().eq('ref_type', 'PURCHASE').gt('sku_qty_apply',0).ne('flagResponse', 1)"
    >
      <template #demandPackageQty="{row}">
        <el-button-group>
          <el-button type="success" size="mini" round>{{row.demandPackageQty}}</el-button>
        </el-button-group>
      </template>
      <template #onWayQty="{row}">
        <el-button-group>
          <el-button type="warning" size="mini" round>{{row.onWayQty}}</el-button>
        </el-button-group>
      </template>
    </data-view>
  </div>
</template>

<script>

export default {
  name: 'purchaseauto',
  data() {
    return {}
  },
  components: {},
  methods: {
    //行编辑选择事件
    selectChange(param) {
      if (param.column.property == 'billPackageUnit') {
        this.$set(param.row, 'billPackageUnit', param.column.selectRow.packageUnit)

        let billPackageRateOld = param.row.billPackageRate
        let billPackageRateNew = param.column.selectRow.packageRate
        let billPackageSkuQty = billPackageRateOld * param.row.billPackageQty
        this.$set(param.row, 'billPackageRate', param.column.selectRow.packageRate)

        //开单数量
        this.$set(param.row, 'billPackageQty', this.utilNum.toFixed(billPackageSkuQty / billPackageRateNew, 2))
      }
    },
    //耗材单位初始化
    syncMatrUnit() {
      //wrapper条件
      let wrapper = this.$newWrapper().eq('flag_base', false)
      this.$refs.dvDataView.setEditQueries('billPackageUnit', wrapper)

      //固定数据筛选参数
      let userParam = {
        viewKey: 'select_matr_unit_purchase',
        checkType: 'radio',
        useMsg: '数据筛选条件：所选耗材的有效请领单位',
        //前一个单元格编辑值为空的提示
        beforeNullMsg: '请先选择耗材',
        //查询单位时的条件字段
        beforeFieldQueryName: 'matrId',
        //下一个编辑单元格
        nextFieldEditName: 'billPackageQty',
      }
      this.$refs.dvDataView.setEditUserParam('billPackageUnit', userParam)
    },

    afterLoad() {
      this.syncMatrUnit()
    },
    extraButtonClick(para) {
      let {key: buttonKey} = para.button
      if (buttonKey == 'purchase_respond') { //采购开单
        let applyAutos = para.data.filter(o => o.refId == null && o.refOrderId == null)
        if (applyAutos instanceof Array) {
          if (applyAutos.length == 0) {
            this.utilMessage.error('请先选择需求单，已经响应的不能再次响应')
            return false
          }
        }
        this.autoRespondPurchase(applyAutos, 0)
      }

      if (buttonKey == 'auto_po_qty') { //填充开单数量
        let applyAutos = para.data
        if (applyAutos.length == 0) {
          this.utilMessage.error('请先选择')
          return
        }
        this.autoRespondPurchase(applyAutos, 1)
      }
      if (buttonKey == 'item_invalid') { //作废订单
        let applyAutos = para.data.filter(o => o.refId == null && o.refOrderId == null)
        if (applyAutos instanceof Array) {
          if (applyAutos.length == 0) {
            this.utilMessage.error('未响应的需求才可以作废')
            return false
          }
        }
        this.respondClose(applyAutos)
      }
      if (buttonKey == 'cp_refresh') { //刷新
        let that = this
        that.$confirm('刷新会执行所有需求，会比较慢，确认执行吗？', '提示', {
          type: 'info'
        }).then(() => {
          that.utilVue.loadShow(true)
          that.$ajax.post('/dept/apply_auto/autoCreateApply').then(resp => {
            that.utilVue.loadHide()
            that.$refs.dvDataView.fetchData()
          })
        })
      }
    },
    /*
     * applyAutos: 选中操作的明细
     * type: 操作的状态   0:响应, 1:填充开单数量
     */
    autoRespondPurchase(applyAutos, type) {
      let that = this
      if (type === 0) {
        this.utilVue.loadShow(true)
        this.$ajax.post('/dept/purchase_auto/toDemand', applyAutos).then(resp => {
          this.utilVue.loadHide()
          if (resp.code == 0) {
            that.$refs.dvDataView.fetchData()
            that.$confirm(`响应成功，生成采购需求单数量:${resp.data.length}，是否打开第一个采购需求单？`, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'info'
            }).then(() => {
              global.utils.openMenu('purchase/demand-purchase/index', {id: resp.data[0].id}, true)
            }).catch(() => {
            })
          }
        })
      }
      //  填充开单数量
      if (type === 1) {
        this.utilVue.loadShow(true)
        this.$ajax.post('/dept/purchase_auto/fillQty', applyAutos).then(resp => {
          this.utilVue.loadHide()
          if (resp.code == 0) {
            that.$refs.dvDataView.fetchData()
            this.utilMessage.success(`填充数量成功，影响记录数量:${resp.data}`)
          }
        })
      }
    },
    respondClose(applyAutos) {
      let that = this
      let params = {
        applyAutos,
        value: ''
      }
      this.$ajax.post('/dept/apply_auto/respondClose', params).then(resp => {
        that.$refs.dvDataView.fetchData()
        that.utilMessage.success('作废成功')
      })
    },
    // 自定义选择聚焦回调
    customSelectFocus(column, row) {
      // 包装名称
      if (column.name == 'billPackageUnit') {
        if (this.strings.isBlank(row.matrId)) {
          this.utilMessage.warning('请先选择商品')
          return
        }
        this.utilSelect.matrUnit(this.billPackageUnitSelect, row.matrId)
      }
    },
    // 单位选择后
    billPackageUnitSelect(row, refName) {
      // 当前选中行
      let currentRow = this.$refs.dvDataView.getCurrentRow()
      let billPackageRateOld = currentRow.billPackageRate
      let billPackageRateNew = row.rate
      let billPackageSkuQty = billPackageRateOld * currentRow.billPackageQty
      this.$set(currentRow, 'billPackageRate', row.rate)
      this.$set(currentRow, 'billPackageUnit', row.unit)
      //换算单位后是否为整数
      if (!this.utilNum.isInt(billPackageSkuQty / billPackageRateNew)) {
        this.utilMessage.warning('开单数量无法自动换算成整数，请手动调整')
        return
      }
      //开单数量
      this.$set(currentRow, 'billPackageQty', this.utilNum.toFixed(billPackageSkuQty / billPackageRateNew, 2))
    },

  },
  computed: {
    //自定义列
    myPropCustomCols() {
      return [
        {
          name: 'demandPackageQty',
          cmode: 'edit'
        },
        {
          name: 'onWayQty',
          cmode: 'edit'
        }
      ]
    }
  },
  props: ['propFlowKey'],
  mounted() {
    this.$refs.dvDataView.ocSetShowCheckBox(true)
  }
}
</script>

<style lang="scss" scoped>
  .container {
    height: 100%;
    background-color: #fff;

    /deep/ .data-view {
      .edit-down-pulldown {
        width: 100% !important;
      }
    }
  }
</style>
